package com.share.servlet;

import com.share.domain.BlogDomain;
import com.share.domain.BlogDomainImpl;
import com.share.domain.CommentDomain;
import com.share.domain.CommentDomainImpl;
import com.share.entity.Blog;
import com.share.entity.Comment;
import com.share.entity.User;
import com.share.servlet.utils.ForwardUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;

/**
 * Created by leeping on 2016/1/12.
 */
public class CommentServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		int blogId = Integer.parseInt(req.getParameter("id"));
		BlogDomain blogDomain = new BlogDomainImpl();
		Blog blog = blogDomain.getBlogById(blogId);
		CommentDomain commentDomain = new CommentDomainImpl();
		List<Comment> comments = commentDomain.getComments(blog.getId());

		req.setAttribute("blog", blog);
		req.setAttribute("comments", comments);
		ForwardUtils.forward(req, resp, "/comment/add.jsp", getServletContext());
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String content = req.getParameter("content");
		Integer blogId = Integer.valueOf(req.getParameter("blogId"));
		BlogDomain blogDomain = new BlogDomainImpl();
		Blog blog = blogDomain.getBlogById(blogId);
		req.setAttribute("blog", blog);
		if (blog == null) {
			req.setAttribute("msg", "文章不存在");
			ForwardUtils.forward(req, resp, "/comment/add.jsp", getServletContext());
			return;
		}
		blog.setCommentNum(blog.getCommentNum() + 1);

		User user = (User) req.getSession().getAttribute("user");
		Comment comment = new Comment();
		comment.setUserId(user.getId());
		comment.setBlogId(blogId);
		comment.setCreateTime(new Timestamp(System.currentTimeMillis()));
		comment.setContent(content);
		CommentDomain commentDomain = new CommentDomainImpl();
		boolean result = commentDomain.save(comment, blog);
		if (result) {
			resp.sendRedirect("/comment/add?id=" + blog.getId());
		} else {
			req.setAttribute("msg", "评论失败");
			ForwardUtils.forward(req, resp, "/comment/add.jsp", getServletContext());
		}
	}
}
